package com.wdh.kjs.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.QuestionListViewAdapter;
import com.wdh.kjs.R;
import com.wdh.kjs.activity.KefuAnswerQuestionActivity;
import com.wdh.kjs.activity.KehuAnswerActivity;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.BusinessType;
import com.wdh.kjs.model.Question;
import com.wdh.kjs.model.QuestionListForApp;
import com.wdh.kjs.model.ShowBusinessForAppmodel;
import com.wdh.kjs.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by feifei on 2016/9/2.
 */
public class KeFuFragment extends Fragment implements  View.OnClickListener {
   /* private String appkey = "23446466";
    private String account="zoupengfei" ;
    private String pw="zoupengfei" ;*/

    private ListView lv_question;
    private Spinner businessType;
    private EditText editText_userquestion;
    private TextView tv_moreQuestion;
    private Button btnSend;

    private ArrayList<Question> questionList=new ArrayList<>();
    private QuestionListForApp questionListForApp;
    private QuestionListViewAdapter mAdapter;
    private ShowBusinessForAppmodel businessForAppmodel;

    private int count=1;
    private int page=1;
    private int rows=5;
    private int totalRecods=0;
    private String partyId="";
    private Map<String,String> describeToAnswer=new HashMap<String,String>();
    private Map<String,String> businessNameTobusinessId=new HashMap<>();
    private final static String DEFAULT_BUSINESS="选择业务";
    private final static String DEFAULT_BUSINESSID="-50";
    private final static String DEFAULT_PARTYID="9999";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_kefu, container, false);
//        MainActivity.llTab.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

//     SharedPreferences sharedPreferences = getActivity().getSharedPreferences("logininfo", Context.MODE_PRIVATE);
//		account = sharedPreferences.getString("loginToken","");
//		pw = sharedPreferences.getString("mima","");
//		FeedbackAPI.mFeedbackCustomInfoMap.put("password", pw);
//		FeedbackAPI.mFeedbackCustomInfoMap.put("loginType", "0");
//		FeedbackAPI.mFeedbackCustomInfoMap.put("uid", account);
//		FeedbackAPI.initOpenImAccount(getActivity().getApplication(), appkey, account, pw);
//        //如果发生错误，请查看logcat日志
//        FeedbackAPI.openFeedbackActivity(getActivity());
//        Map<String, String> map = new HashMap<>();
//        map.put("pageTitle", "客服");
//        map.put("sendBtnTextColor", "white");
//        map.put("sendBtnBgColor", "blue");
//        FeedbackAPI.setUICustomInfo(map);
////如果希望使用Fragment方式打开请调用一下API
//        FeedbackAPI.getFeedbackFragment();
        page=1;
        rows=5;
        count=1;
        getPartyId();
        initView(view);
        initBusinessType();
        initQuestionListview();
        return view;
    }

    private void initView(View view) {
        lv_question=(ListView)view.findViewById(R.id.lv_msg);
        businessType=(Spinner)view.findViewById(R.id.spn_msg_from);
        editText_userquestion=(EditText)view.findViewById(R.id.editTxt_msg);
        btnSend=(Button)view.findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);
        lv_question.setOnItemClickListener(new MyListViewItemlistener());
        tv_moreQuestion=(TextView) view.findViewById(R.id.moreQuestion);
        tv_moreQuestion.setOnClickListener(this);
    }

    private void initBusinessType(){
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_ShowBusiness_For_App, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
               // System.out.println("返回的结果:"+responseInfo.result);
                businessForAppmodel = gson.fromJson(responseInfo.result, ShowBusinessForAppmodel.class);
                if (businessForAppmodel.isSuccess()) {
                    businessNameTobusinessId.clear();
                    ArrayList<BusinessType> arrayList=businessForAppmodel.getBusinessType();
                    ArrayList<String> list=new ArrayList<String>();
                    list.add(DEFAULT_BUSINESS);
                    businessNameTobusinessId.put(DEFAULT_BUSINESS,DEFAULT_BUSINESSID);
                    for(BusinessType btype:arrayList){
                        list.add(btype.getBusinessName());
                        businessNameTobusinessId.put(btype.getBusinessName(),btype.getBusinessId());
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item,list);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    businessType.setAdapter(adapter);
                }
                else {
                    businessNameTobusinessId.clear();
                //    ArrayList<BusinessType> arrayList=businessForAppmodel.getBusinessType();
                    ArrayList<String> list=new ArrayList<String>();
                    list.add(DEFAULT_BUSINESS);
                    businessNameTobusinessId.put(DEFAULT_BUSINESS,DEFAULT_BUSINESSID);
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item,list);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    businessType.setAdapter(adapter);
                    ToastUtils.showShort(getContext(), "获取业务类型失败");
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                ArrayList<String> list=new ArrayList<String>();
                businessNameTobusinessId.clear();
                list.add(DEFAULT_BUSINESS);
                businessNameTobusinessId.put(DEFAULT_BUSINESS,DEFAULT_BUSINESSID);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item,list);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                businessType.setAdapter(adapter);
                ToastUtils.showShort(getContext(), "网络异常！");
            }
        });
    }

    private void initQuestionListview(){
        getQuestionList();
    }

    @Override
    public void onStop() {
        super.onStop();
//        MainActivity.llTab.setBackgroundColor(getResources().getColor(R.color.white));
    }

    @Override
    public void onPause() {
        super.onPause();
//        MainActivity.llTab.setBackgroundColor(getResources().getColor(R.color.white));
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.btn_send:{
                sendMsg();
                break;
            }
            case R.id.moreQuestion:{
                getMoreQuestion();
                break;
            }
        }
    }

    private void sendMsg(){
        TextView tv=(TextView)businessType.getSelectedView();
        if(tv==null)
        {
            ToastUtils.showShort(getContext(), "请选择业务类型!");
            return;
        }
        String business=tv.getText().toString().trim();
        if(business==null||business.length()==0) {
            return;
        }else if(business.equals(DEFAULT_BUSINESS)){
            if(businessNameTobusinessId.size()==1) {
                initBusinessType();
            }
            else {
                ToastUtils.showShort(getContext(), "请选择业务类型!");
            }
            return;
        }
        String user_question=editText_userquestion.getText().toString();
        if(user_question==null||user_question.length()==0)
        {
            ToastUtils.showShort(getContext(), "请输入要搜索的内容");
            return;
        }
        String businessId=businessNameTobusinessId.get(business);
       // System.out.println(partyId+":"+businessId+":"+user_question);
        editText_userquestion.getText().clear();
        Intent intent=new Intent(getContext(), KehuAnswerActivity.class);
        intent.putExtra("partyId",partyId);
        intent.putExtra("businessId",businessId);
        intent.putExtra("questionDescribe",user_question);
        startActivity(intent);
    }

    private void getQuestionList() {
       // System.out.println("getQuestionList");
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_ShowQuestionList_For_App, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                questionListForApp = gson.fromJson(responseInfo.result, QuestionListForApp.class);
                if (questionListForApp.getSuccess()) {
                    questionList=questionListForApp.getQuestionList();
                    addDescribeToAnswer(questionList);
                    totalRecods=questionListForApp.getTotalrecords();
                    mAdapter=new QuestionListViewAdapter(getContext(),questionList);
                    lv_question.setAdapter(mAdapter);
                }
                else {
                    ToastUtils.showShort(getContext(), questionListForApp.getMsg());
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getContext(), "网络异常！");
            }
        });
    }

    private void getMoreQuestion(){
        if(questionList.size()>=totalRecods){
            ToastUtils.showShort(getContext(), "没有更多数据了！");
            return;
        }
        page++;
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_ShowQuestionList_For_App, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                questionListForApp = gson.fromJson(responseInfo.result, QuestionListForApp.class);
                if (questionListForApp.getSuccess()) {
                    ArrayList<Question> newQuestionList=questionListForApp.getQuestionList();
                    addDescribeToAnswer(newQuestionList);
                    for(Question question:newQuestionList){
                        questionList.add(question);
                    }
                    if(mAdapter==null){
                        mAdapter=new QuestionListViewAdapter(getContext(),questionList);
                        lv_question.setAdapter(mAdapter);
                    }
                    else {
                        mAdapter.notifyDataSetChanged();
                    }
                }
                else{
                    page--;
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                page--;
                ToastUtils.showShort(getContext(), "网络异常！");
            }
        });
    }

    private void addDescribeToAnswer(ArrayList<Question> arrayList){
       // System.out.println("addDescribeToAnswer");
        for(Question q:arrayList){
         //   System.out.println(count+"."+q.getQuestionDescribe());
            q.setQuestionDescribe(count+"."+q.getQuestionDescribe());
            count++;
            describeToAnswer.put(q.getQuestionDescribe(),q.getQuestionResponse());
        }
    }

    class MyListViewItemlistener implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String questionDescribe=questionList.get(position).getQuestionDescribe();
            String answer=describeToAnswer.get(questionDescribe);
            //去掉“数字.”
            String str[]=questionDescribe.split("\\.");
            questionDescribe="";
            int i;
            for(i=1;i<str.length;i++){
                questionDescribe=questionDescribe+str[i];
            }
            QuestionListForApp.staticTitle=questionDescribe;
            QuestionListForApp.staticAnswer=answer;
            Intent intent=new Intent(getContext(), KefuAnswerQuestionActivity.class);
            startActivity(intent);
        }
    }

    private void getPartyId(){
        SharedPreferences share =getContext().getSharedPreferences("logininfo", Activity.MODE_PRIVATE);
        partyId = share.getString("loginToken",DEFAULT_PARTYID);
    }

}
